# -*- coding: utf-8 -*-
# Demo: MACD strategy
# src: ./test_backtest/MACD_JCSC.py
# jupyter: ./test_backtest/QUANTAXIS回测分析全过程讲解.ipynb
# paper: ./test_backtest/QUANTAXIS回测分析全过程讲解.md

import QUANTAXIS as QA
import numpy as np
import pandas as pd
import datetime
st1 = datetime.datetime.now()
# define the MACD strategy

# create account
user = QA.QA_User(username='quantaxis', password='quantaxis')
portfolio = user.new_portfolio('backtest_benchmark')
Account = portfolio.new_account(account_cookie='benchmark_test', init_cash=1e5, market_type=QA.MARKET_TYPE.INDEX_CN)
Broker = QA.QA_BacktestBroker()

# get data from mongodb
start = '2018-01-01'
end = '2020-08-30'
data = QA.QA_fetch_index_day_adv(['510050'], start, end)
# data_forbacktest = data.select_time('2019-07-01', '2019-11-01')

day_index = 0
for items in data.panel_gen:
    if day_index == 0:
        for item in items.security_gen:
            order = Account.send_order(
                code=item.code[0],
                time=item.date[0],
                amount=int(Account.cash_available / item.price[0] / 101) * 100,
                towards=QA.ORDER_DIRECTION.BUY,
                price=item.price[0],
                order_model=QA.ORDER_MODEL.CLOSE,
                amount_model=QA.AMOUNT_MODEL.BY_AMOUNT
            )
            # print(item.to_json()[0])
            Broker.receive_order(QA.QA_Event(order=order, market_data=item))
            trade_mes = Broker.query_orders(Account.account_cookie, 'filled')
            res = trade_mes.loc[order.account_cookie, order.realorder_id]
            order.trade(res.trade_id, res.trade_price, res.trade_amount, res.trade_time)
    elif day_index == len(data.index.levels[0]) - 1:
        for item in items.security_gen:
            order = Account.send_order(
                code=item.code[0],
                time=item.date[0],
                amount=Account.sell_available.get(item.code[0], 0),
                towards=QA.ORDER_DIRECTION.SELL,
                price=item.price[0],
                order_model=QA.ORDER_MODEL.MARKET,
                amount_model=QA.AMOUNT_MODEL.BY_AMOUNT
            )
            # print
            Broker.receive_order(QA.QA_Event(
                order=order, market_data=item))
            trade_mes = Broker.query_orders(
                Account.account_cookie, 'filled')
            res = trade_mes.loc[order.account_cookie, order.realorder_id]
            order.trade(res.trade_id, res.trade_price,
                        res.trade_amount, res.trade_time)
    day_index += 1
    Account.settle()

print('TIME -- {}'.format(datetime.datetime.now()-st1))
print(Account.history)
print(Account.history_table)
print(Account.daily_hold)

# create Risk analysis
Risk = QA.QA_Risk(Account)

# Account.save()
# Risk.save()
# Risk.plot_assets_curve().show()

print(Risk.message)
print(Risk.assets)
Risk.plot_assets_curve().show()
# plt=Risk.plot_dailyhold()
# plt.show()
# plt1=Risk.plot_signal()
# plt.show()

# performance=QA.QA_Performance(Account)
# plt=performance.plot_pnlmoney(performance.pnl_fifo)
# plt.show()
# Risk.assets.plot()
# Risk.benchmark_assets.plot()

# save result

#account_info = QA.QA_fetch_account({'account_cookie': 'user_admin_macd'})
#account = QA.QA_Account().from_message(account_info[0])
# print(account)
